from PySide6.QtWidgets import QWidget, QHBoxLayout
from PySide6.QtCore import Qt, QPropertyAnimation, QThread, Signal

from GUICore.widgets import Loading
from .functions import ResourceLoader


class LoadingWindow(QWidget):
    loaded = Signal(bool)

    def __init__(self, image_path):
        super().__init__()
        self.dragging = False
        self.offset = None

        layout = QHBoxLayout()
        self.setLayout(layout)
        self.progress = Loading(image_path)
        self.progress.stopRequested.connect(self.handle_stop)
        layout.addWidget(self.progress)

        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setStyleSheet("background: transparent;")
        self.setFixedSize(self.progress.size())

        self.quit_anim = QPropertyAnimation(self.progress, b"value", self)
        self.quit_anim.setDuration(300)
        self.quit_anim.finished.connect(self.thread_stop)

        self.thread = QThread()
        self.loader = ResourceLoader()

        self.load_anim = QPropertyAnimation(self.progress, b"value", self)
        self.load_anim.setDuration(10)
        self.load_anim.finished.connect(lambda: self.loader.resume())

        self.setup_loading()

    def setup_loading(self):
        self.thread.started.connect(self.loader.perform_loading)
        self.thread.finished.connect(self.close)
        self.loader.moveToThread(self.thread)
        self.loader.progress_updated.connect(self.update_progress)
        self.loader.finished.connect(self.thread.quit)
        self.loader.finished.connect(self.openMainWindow)

    def update_progress(self, value):
        self.load_anim.setStartValue(self.progress.get_value())
        self.load_anim.setEndValue(value)
        self.load_anim.start()
        # self.progress.set_value(value)

    def openMainWindow(self):
        self.thread.wait()
        self.loaded.emit(bool(1))
        self.close()

    def handle_stop(self):
        self.quit_anim.setStartValue(self.progress.get_value())
        self.quit_anim.setEndValue(0)
        self.loader.stop()
        self.quit_anim.start()

    def thread_stop(self):
        self.thread.quit()  # 请求线程退出
        self.thread.wait(500)  # 等待最多500ms
        self.close()

    def showEvent(self, event):
        self.thread.start()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = True
            self.offset = event.globalPosition().toPoint() - self.pos()

    def mouseMoveEvent(self, event):
        if self.dragging and self.offset:
            self.move(event.globalPosition().toPoint() - self.offset)

    def mouseReleaseEvent(self, event):
        self.dragging = False
